<template>
    <div>
        <el-row>
            <el-col :span="22" id="selectdiv">

                <el-form :inline="true" :model="selectData" class="demo-form-inline">
                    
                    <el-form-item label="通知名字" label-position="left">
                        <el-input v-model="selectData.textTitle" placeholder="通知名字"></el-input>
                    </el-form-item>
                    
                    <el-form-item label="通知链接" label-position="left">
                        <el-input v-model="selectData.textUrl" placeholder="通知链接"></el-input>
                    </el-form-item>
                    <el-form-item style="width: 80px;">
                        <el-button size="small" type="primary" @click="findByData">查询</el-button>
                    </el-form-item>
                    <el-form-item style="width: 80px;">
                        <el-button size="small" type="primary" @click="clear">清除</el-button>
                    </el-form-item>
                </el-form>

            </el-col>
            <el-col :span="2" style="margin-bottom: 22px;">
                <div class="grid-content bg-purple-light">
                    <el-button size="small" type="primary" @click="opendialog"
                        style="margin-top:6px;z-index:1;position:relative">新增</el-button>
                    <el-dialog title="新增信息" :visible.sync="dialogFormVisible" id="adddialog"
                        :close-on-click-modal="false" @close="resetForm">
                        <el-upload ref="fileUploadForm" action="" :multiple="false" :auto-upload="false" 
                        :show-file-list="isShow"
                        :file-list="fileList"
                            :http-request="handleFileUploadSubmit" :on-change="handleFileChanged" 
                            accept=".pdf,.doc,.docx"
                            
                            :on-success="handleSuccess">
                            <el-row>
                                <el-col style="display: flex; text-align: center; width: 400px">
                                    <el-input :value="currentFileName" placeholder="请选择文件" readonly />
                                    <el-button type="primary"  style="margin-left: 20px">选择文件</el-button>
                                </el-col>
                            </el-row>
                        </el-upload>
                        
                        <el-row style="margin-top: 30px; margin-bottom: 30px">
                            <el-col style="text-align: center">
                                <el-button @click="clearFile">清空</el-button>
                                <el-button type="success" style="margin-left: 20px" @click="uploadPrj">上传云端</el-button>
                                <el-button type="success" style="margin-left: 20px" @click="submitFile">确认</el-button>
                            </el-col>
                        </el-row>
                        


                            
                        
                    </el-dialog>
                </div>
            </el-col>
        </el-row> 
        <!-- 新增按钮 -->


        <!-- 表格展示 -->
        <el-table :data="tableData" :height="tableHeight" style="width: 100%" border>
            <el-table-column prop="textId" label="ID"></el-table-column>
            <el-table-column prop="textTitle" label="通知题目"></el-table-column>
            <el-table-column prop="textUrl" label="Url">
                <template slot-scope="scope">
                    <a :href="scope.row.textUrl" target="_blank" class="buttonText">{{scope.row.textUrl}}</a>
                </template>
            </el-table-column>
            
            <!-- 其他列... -->
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
        </el-pagination>

        
    </div>
</template>

<script>
    export default {
        data() {
            return {
                tableHeight: window.innerHeight - 200,
                headers: { 'Content-Type': 'multipart/form-data' },
                dialogFormVisible: false,
                formLabelWidth: '120px',
                file: null,
                fileList:[],
                isShow:false,
                currentFileName:'',
                selectData: {
                    textTitle: '',
                    textUrl: '',
                },
                tableData: []
                , // 表格数据
                currentPage: 1, // 当前页码
                pageSize: 10, // 每页显示数量
                totalCount: 0, // 总记录数
                havesubmitPrj: {
                    textId: '',
                    textUrl: '',
                    textTitle: '',
                    textCreatetime: ''
                },
                postprojectData: {
                    textId: '',
                    textUrl: '',
                    textTitle: '',
                    textCreatetime: ''
                },
                
            };
        },
        methods: {
            getHeight() {
                console.log("tableHeight:" + this.tableHeight);
                this.tableHeight = window.innerHeight - 200;
            },
            opendialog(){
                this.dialogFormVisible = true
                this.file = null;
                this.currentFileName = null;
                this.havesubmitPrj.textTitle = null;
                this.havesubmitPrj.textUrl = null;

                this.postprojectData.textTitle = null;
                this.postprojectData.textUrl = null;
            },
            async fetchData() {
                // 获取后台数据，假设使用axios
                
                this.$axios({
                    method: 'post',
                    url: 'http://localhost:8080/textinfo',
                    data: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        textTitle: this.selectData.textTitle,
                        textUrl: this.selectData.textUrl
                    },
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(res => {
                    this.totalCount = res.data.data.total;
                    this.tableData = res.data.data.rows;
                    console.log('tableData',this.tableData);
                    
                })

            },
            downloadFile() {
                // 创建隐藏的可下载链接
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = this.havesubmitPrj.textUrl || this.postprojectData.textUrl;
                link.download = this.havesubmitPrj.textTitle || this.postprojectData.textTitle;

                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
            handleFileChanged(selectedFile,fileList) {
                // 文件列表修改为选择的文件
                if (fileList.length > 0) {
                    this.fileList = [fileList[fileList.length - 1]] 
                     // 这一步，是 展示最后一次选择的csv文件
                }
                
                this.file = selectedFile;
                console.log('file',this.file);
                // 提示框展示为选择的文件的文件名
                var filename = selectedFile.name;
                var fileName = filename.split('.').slice(0, -1).join('.');
                var PatternFileName = fileName
                this.currentFileName = PatternFileName;
                this.postprojectData.textTitle = this.currentFileName;


            },

            /**
             * 清空待上传的文件列表
             * */
            clearFile() {
                // 待上传的文件列表清空
                this.file = null;
                // 提示框展示的文件名清空
                this.currentFileName = '';
                this.fileList=[];
                this.postprojectData.textTitle = null;
                this.postprojectData.textUrl = null;
                this.havesubmitPrj.textTitle = null;
                this.havesubmitPrj.textUrl = null;
            },

            /**
             * 点击【上传】按钮时要进行的操作
             * */
            uploadPrj() {
                
                    const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
                    
                    // TODO 还可以进行文件校验等操作
                    if (this.file == null) {
                        this.$alert('请选择文件后再上传！', '提示', {
                            type: 'warning'
                        });
                        return;
                    }
                    const fileMimeType = this.file.raw.type;
                    if (!allowedTypes.includes(fileMimeType)) {
                        alert('只能上传PDF、Word');
                        // 清除已选中的非法文件
                        this.clearFile();
                        return;
                    }
                    // 校验无误将要上传，这里会调用 http-request 所绑定的方法
                    
                    this.$refs.fileUploadForm.submit();
                    
                    
                

            },
            async handleSuccess(response, file) {
                // 假设后端返回的是上传到OSS后的图片URL
                const fileName = this.file.name;
                var fileName1 = fileName.split('.').slice(0, -1).join('.');
                this.postprojectData.textTitle = fileName1 ;
                this.postprojectData.textUrl = response.data.data;
                console.log('file'+this.file);

            },
            /**
             * 发送文件上传的网络请求
             * */
            handleFileUploadSubmit({ file }) {
                
                    // 创建一个表单，用于存放请求数据(主要是文件)
                    const fileFormData = new FormData();
                    // 在表单中添加要发送给接口的数据
                    
                    fileFormData.append('file', file);
                    
                    // 使用 axios 发送文件上传请求，并监听文件上传进度
                    
                    try {
                        this.$axios({
                            method: 'post',
                            url: 'http://localhost:8080/textinfo/upload',
                            data: fileFormData,

                        }).then(res => {
                            if (res.data.code == 1) {
                                this.handleSuccess(res);
                                this.$message.success('上传文件成功！');
                                this.file = null;
                            }

                        })

                    } catch (error) {
                        console.error('上传失败:', error);
                        this.$message.error('上传图片到OSS失败!');
                    }
                


            },
            submitFile() {
               
                    this.$confirm('提交后通知会被展示, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$axios({
                            method: 'post',
                            url: "http://localhost:8080/textinfo/submit",
                            data: JSON.stringify(this.postprojectData),
                            headers: { 'Content-Type': 'application/json' },
                        }).then(res => {
                            if (res.data.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: '提交成功!'
                                });
                                this.isShow = true;
                                this.fetchData();
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '提交失败，请联系管理员!'
                                });
                            }
                        })

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消提交'
                        });
                    });
                

            },
            resetForm(){
                this.file=null;
                this.currentFileName = null;
                this.havesubmitPrj.textTitle=null;
                this.havesubmitPrj.textUrl=null;
                this.fileList =[];
                this.postprojectData.textTitle = null;
                this.postprojectData.textUrl = null;
                this.dialogFormVisible = false;
            },
            findByData(){
                this.fetchData();
            },
           
            clear(){
                this.selectData.textTitle ='';
                this.selectData.textUrl ='';
                this.fetchData();
            },

            

            cancel() {
                this.dialogFormVisible = false
            },

           
            
            
            

            handleSizeChange(size) {
                this.pageSize = size;
                this.fetchData();
            },
            handleCurrentChange(page) {
                this.currentPage = page;
                this.fetchData();
            },
        },
        created() {
            window.addEventListener('resize', this.getHeight)
        },
        mounted() {
            this.fetchData();
            this.resetForm();
        },
    };
</script>
<style lang="less">
    #selectdiv {
        .el-form-item {
            width: 40%;
            margin-right: 0;

            .el-form-item__content {
                line-height: 40px;
                position: relative;
                font-size: 14px;
                width: 140px;
            }
        }

    }

    #adddialog {
        .el-form-item {
            width: 70%;
            margin-right: 0;

            .el-form-item__content {
                line-height: 40px;
                width: 70%;
                font-size: 14px;
            }
        }

    }

    .parentBox {
        padding: 20px;
    }

    .iconBox i {
        width: 100px;
        height: 100px;
        text-align: center;
        line-height: 100px;
        font-size: 20px;
        color: #8c939d;
        font-weight: bold;
        border: 1px #8c939d dashed;
        border-radius: 4px;
        background: rgb(251, 253, 255);
    }

    .iconBox i:hover {
        border: 1px rgb(64, 158, 255) dashed;
    }

    .el-image {
        width: 100px;
        height: 100px;
        border-radius: 4px;
        border: 1px solid rgb(192, 204, 218);
    }

    .gbtpBox {
        position: relative;
    }

    .gbtpBox span {

        top: -110px;
        left: 90px;
        cursor: pointer;
        font-size: 16px;
        border-radius: 50%;
        width: 16px;
        height: 16px;
        text-align: center;
        line-height: 16px;
        background: rgb(245, 108, 108);
        color: #fff;
    }

    .gbtpBox span:hover {
        background: rgb(247, 137, 137);
        color: #fff;
    }

    ::v-deep .avatar-uploader {
        height: 0px;
    }
</style>